package com.bjbn.tasks;

import com.bjbn.service.FzLocation1Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class FzLocation1ProcessingTask implements CommandLineRunner {

    @Autowired
    private FzLocation1Service fzLocation1Service;

    private boolean hasStarted = false;

    @Override
    public void run(String... args) throws Exception {
        log.info("Application started. Loading FZ-Location-1 CSV data and starting continuous processing...");
        startFzLocation1ContinuousProcessing();
    }

    @Scheduled(cron = "0 0 2 * * ?") // Run at 2 AM daily
    public void scheduledFzLocation1Reload() {
        log.info("Scheduled FZ-Location-1 CSV data reload started");
        reloadFzLocation1Data();
    }

    public void startFzLocation1ContinuousProcessing() {
        if (hasStarted) {
            log.info("FZ-Location-1 continuous processing has already been started. Skipping...");
            return;
        }
        try {
            fzLocation1Service.startFzLocation1ContinuousProcessing();
            hasStarted = true;
            log.info("FZ-Location-1 continuous processing started successfully");
        } catch (Exception e) {
            log.error("Error starting FZ-Location-1 continuous processing: {}", e.getMessage(), e);
        }
    }

    public void stopFzLocation1ContinuousProcessing() {
        fzLocation1Service.stopFzLocation1ContinuousProcessing();
        hasStarted = false;
        log.info("FZ-Location-1 continuous processing stopped");
    }

    public void reloadFzLocation1Data() {
        fzLocation1Service.reloadFzLocation1Data();
        log.info("FZ-Location-1 CSV data reloaded successfully");
    }

    public boolean isFzLocation1HasStarted() {
        return hasStarted;
    }

    public boolean isFzLocation1Running() {
        return fzLocation1Service.isFzLocation1Running();
    }
}

